//
//  SLTool.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/5.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import Foundation
import Foundation
import AdSupport
import SystemConfiguration
import CoreTelephony
import SystemConfiguration.CaptiveNetwork
import DCURLRouter
class SLTool {
    class public func getCurrentVc() -> UIViewController{
        let currentVc = DCURLRouter().currentViewController()
        return currentVc
    }
    /// 获取APP版本
    /// - Returns:  
    class public func getVersion() -> String {
        if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            return appVersion
        }
        return ""
    }
    class func isJailBroken() -> Bool {
           //判断设备上是否安装了这些程序
          let apps = ["/APPlications/Cydia.app","/APPlications/limera1n.app","/APPlications/greenpois0n.app","/APPlications/blackra1n.app","/APPlications/blacksn0w.app","/APPlications/redsn0w.app","/APPlications/Absinthe.app"]
           for app in apps {
               //通过文件管理器，判断在指定的目录下，是否在对应的应用程序。如果存在的话。就表示当前设备为越狱设备。
               if FileManager.default.fileExists(atPath: app){
                   return true
               }
           }
           return false
       }
    /// 获取设备型号
    /// - Returns:  
    class public func getDeviceModel() -> String {
        let deviceModel = UIDevice.current.model
        return deviceModel
    }
    /// 获取系统版本
    /// - Returns:  
    class public func getSystemVersion() -> String {
        let systemVersion = UIDevice.current.systemVersion
        return systemVersion
    }
    ///获取系统版本
       class func  getDeviceSystemVersion() -> String {
           return UIDevice.current.systemVersion
       }
       
       ///获取系统名称
       class func  getDeviceSystemName() -> String {
           return UIDevice.current.systemName
       }

       ///获取系统名称 localized version of model
       class func  getDeviceLocalizedModel() -> String {
           return UIDevice.current.localizedModel
       }
       
       ///获取设备名称 如 XXX的iphone
       class func  getDeviceUserName() -> String {
           return UIDevice.current.name
       }
       ///获取总的内存
       class func  getDeviceDiskTotalSize() -> String {
           return fileSizeToString(fileSize:  getTotalDiskSize())
       }
       
       ///获取可用的内存
       class func  getDeviceAvalibleDiskSize() -> String {
           return fileSizeToString(fileSize:  getAvailableDiskSize())
       }
       
       ///获取运营商
       class func  getDeviceSupplier() -> String {
           return  deviceSupplier()
       }
       
       /// 获取当前设备IP
       class func  getDeviceIP() -> String {
           return  deviceIP() ?? ""
       }
       ///获取设备名称
       class func  getDeviceName() -> String {
           return  deviceName()
       }
    

    /// 获取网络类型
    static func getNetworkType() -> String {
            var zeroAddress = sockaddr_storage()
            bzero(&zeroAddress, MemoryLayout<sockaddr_storage>.size)
            zeroAddress.ss_len = __uint8_t(MemoryLayout<sockaddr_storage>.size)
            zeroAddress.ss_family = sa_family_t(AF_INET)
            let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
                $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { address in

                    SCNetworkReachabilityCreateWithAddress(nil, address)
                }
            }
            guard let defaultRouteReachability = defaultRouteReachability else {
                return "NONE"
            }
            var flags = SCNetworkReachabilityFlags()
            let didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)
            
            guard didRetrieveFlags == true,
                  (flags.contains(.reachable) && !flags.contains(.connectionRequired)) == true
            else {
                return "NONE"
            }
            if flags.contains(.connectionRequired) {
                return "NONE"
            } else if flags.contains(.isWWAN) {
                return self.cellularType()
            } else {
                return "WiFi"
            }
        }
        
        /// 获取蜂窝数据类型
    static  func cellularType() -> String {
            let info = CTTelephonyNetworkInfo()
            var status: String
            
            if #available(iOS 12.0, *) {
                guard let dict = info.serviceCurrentRadioAccessTechnology,
                      let firstKey = dict.keys.first,
                      let statusTemp = dict[firstKey] else {
                    return "NONE"
                }
                status = statusTemp
            } else {
                guard let statusTemp = info.currentRadioAccessTechnology else {
                    return "NONE"
                }
                status = statusTemp
            }
            
            if #available(iOS 14.1, *) {
                if status == CTRadioAccessTechnologyNR || status == CTRadioAccessTechnologyNRNSA {
                    return "5G"
                }
            }
            
            switch status {
            case CTRadioAccessTechnologyGPRS,
                CTRadioAccessTechnologyEdge,
            CTRadioAccessTechnologyCDMA1x:
                return "2G"
            case CTRadioAccessTechnologyWCDMA,
                CTRadioAccessTechnologyHSDPA,
                CTRadioAccessTechnologyHSUPA,
                CTRadioAccessTechnologyeHRPD,
                CTRadioAccessTechnologyCDMAEVDORev0,
                CTRadioAccessTechnologyCDMAEVDORevA,
            CTRadioAccessTechnologyCDMAEVDORevB:
                return "3G"
            case CTRadioAccessTechnologyLTE:
                return "4G"
            default:
                return "NONE"
            }
        }


        //获取本机ip

    static func getLocalIP() -> String? {

        var addresses = [String]()
           var ifaddr : UnsafeMutablePointer<ifaddrs>? = nil
           if getifaddrs(&ifaddr) == 0 {
               var ptr = ifaddr
               while (ptr != nil) {
                   let flags = Int32(ptr!.pointee.ifa_flags)
                   var addr = ptr!.pointee.ifa_addr.pointee
                   if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) {
                       if addr.sa_family == UInt8(AF_INET) /*|| addr.sa_family == UInt8(AF_INET6)*/ {
                           var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                           if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count),nil, socklen_t(0), NI_NUMERICHOST) == 0) {
                               if let address = String(validatingUTF8:hostname) {
                                   addresses.append(address)
                               }
                           }
                       }
                   }
                   ptr = ptr!.pointee.ifa_next
               }
               freeifaddrs(ifaddr)
           }
           return addresses.first
        }
    class func  getDeviceBatteryLevel() -> String{
        UIDevice.current.isBatteryMonitoringEnabled = true
        if UIDevice.current.batteryState != .unknown {
                // 电池状态不为unknown
            let batteryLevel = UIDevice.current.batteryLevel // 获取电池电量
                print("电池电量: \(batteryLevel)")
            let b = Int(batteryLevel*100)
            return "\(b)"
            } else {
                print("无法获取电池信息")
            }
        return ""
    }
    class func  getDeviceBatterySratus() -> String {
        // 电池状态
        let batteryState = UIDevice.current.batteryState
        switch batteryState {
                // 充电
        case .charging:
            return "1"
                // 充满
        case .full:
            break
                // 未知，可能是模拟器
        case .unknown:
            break
                // 未接入电源
        case .unplugged:
            break
        default: break
                }
        return "0"
    }
    static func getCurrentWiFiInfo() -> (SSID: String, BSSID: String)? {
        var SSID: String = ""
        var BSSID: String = ""

       let wifiInterfaces = CNCopySupportedInterfaces()
       guard wifiInterfaces != nil else {
           return (SSID, BSSID)
       }

       let interfaceArr = CFBridgingRetain(wifiInterfaces) as! [String]
       if interfaceArr.count > 0 {
           let interfaceName = interfaceArr[0] as CFString
           let ussafeInterfaceData = CNCopyCurrentNetworkInfo(interfaceName)

           if ussafeInterfaceData != nil {
               let interfaceData = ussafeInterfaceData as! [String: Any]
               SSID = interfaceData["SSID"]! as! String
               BSSID = interfaceData["BSSID"]! as! String
           }
       }
       return (SSID, BSSID)
     
    }
}
extension SLTool {
    ///获取运营商
        private class func  deviceSupplier() -> String {
            let info = CTTelephonyNetworkInfo()
            var supplier:String = ""
            if #available(iOS 12.0, *) {
                if let carriers = info.serviceSubscriberCellularProviders {
                    if carriers.keys.count == 0 {
                        return "无手机卡"
                    } else { //获取运营商信息
                        for (index, carrier) in carriers.values.enumerated() {
                            guard carrier.carrierName != nil else { return "" }
                            //查看运营商信息 通过CTCarrier类
                            if index == 0 {
                                supplier = carrier.carrierName!
                            } else {
                               supplier = supplier + "," + carrier.carrierName!
                            }
                        }
                        if supplier == "--,--"{
                            return ""
                        }
                        return supplier
                    }
                } else{
                    return ""
                }
            } else {
                if let carrier = info.subscriberCellularProvider {
                    guard carrier.carrierName != nil else { return "" }
                    return carrier.carrierName!
                } else{
                    return ""
                }
            }
        }
        /// 获取当前设备IP
    private class func  deviceIP() -> String?  {
        var address: String?
          var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
          guard getifaddrs(&ifaddr) == 0 else {
              return nil
          }
          guard let firstAddr = ifaddr else {
              return nil
          }
          for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
              let interface = ifptr.pointee

              // Check for IPV4 or IPV6 interface

              let addrFamily = interface.ifa_addr.pointee.sa_family

              if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {

                  let name = String(cString: interface.ifa_name)
                  if name == "en0" {
                      // Convert interface address to a human readable string
                      var addr = interface.ifa_addr.pointee
                      var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                      getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                      address = String(cString: hostName)
                  }
              }
          }
          freeifaddrs(ifaddr)
          return address
        }
        
        ///获取cpu核数类型
        private class func  deviceCpuCount() -> Int {
            var ncpu: UInt = UInt(0)
            var len: size_t = MemoryLayout.size(ofValue: ncpu)
            sysctlbyname("hw.ncpu", &ncpu, &len, nil, 0)
            return Int(ncpu)
        }

        private class func  deviceName() -> String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
        private class func blankof<T>(type:T.Type) -> T {
            let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
            let val = ptr.pointee
            return val
        }
        /// 磁盘总大小
        private class func  getTotalDiskSize() -> Int64 {
            let size = ProcessInfo.processInfo.physicalMemory
            return Int64(size)
        }
        /// 磁盘可用大小
        private class func  getAvailableDiskSize() -> Int64 {
            var fs = blankof(type: statfs.self)
            if statfs("/var",&fs) >= 0{
                return Int64(UInt64(fs.f_bsize) * fs.f_bavail)
            }
            return -1
        }
        /// 将大小转换成字符串用以显示
        private class func fileSizeToString(fileSize:Int64) -> String {
            let fileSize1 = CGFloat(fileSize)
            return "\(fileSize)"

        }
}
import Network
import DCURLRouter
class NetworkMonitor {
     private var monitor: NWPathMonitor
     private var queue: DispatchQueue
    var alert:UIAlertController?
     init() {
         monitor = NWPathMonitor()
         queue = DispatchQueue.global(qos: .background)
     }
     func startMonitoring() {
         monitor.start(queue: queue)
         monitor.pathUpdateHandler = { path in
             print("--------network:\(path.status)")
         if path.status == .satisfied {

             NotificationCenter.default.post(name: NSNotification.Name("NetworkReachability"), object: nil)
             DispatchQueue.main.async {
                 if let a = self.alert{
                     a.dismiss(animated: true)
                 }
             }
         } else if path.status == .requiresConnection {
         }else{
             NotificationCenter.default.post(name: NSNotification.Name("NetworkDisconnected"), object: nil)
             DispatchQueue.main.async {
//                 self.showNetworkPermissionDeniedAlert()
             }
         }
         if path.usesInterfaceType(.wifi) {
             print("--------network type:wifi")
         } else if path.usesInterfaceType(.cellular) {
             print("--------network type:蜂窝")
             }
         }
     }
    func showNetworkPermissionDeniedAlert() {
        self.alert = UIAlertController(title: "Network connection failed", message: "Please allow the notification permission to use the network services in the settings", preferredStyle: .alert)
        self.alert!.addAction(UIAlertAction(title: "Setting", style: .default, handler: { _ in
            // 引导用户到应用的设置页面
            if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(appSettings, options: [:]) { _ in
                }
            }
            self.alert?.dismiss(animated: true)
        }))
        self.alert!.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: { _ in
        }))
        DCURLRouter.present(self.alert!, animated: true, completion: nil)
    }
     func stopMonitoring() {
         monitor.cancel()
     }
}
